<template>
  <basic-container>
    <avue-crud :option="option" :table-loading="loading" :data="resData" :page.sync="page" :permission="permissionList"
      :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel"
      @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange"
      @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
      <template #menu="{ row, index, size }">
        <el-button type="text" @click="handleReview(row, index)" v-if="row.auth_status_text === '待审核'">审核</el-button>
        <el-button type="text" @click="handleView(row, index)" v-else>查看</el-button>
      </template>

      <!-- 投诉类型 -->
      <template slot-scope="{ row }" slot="complaintType">
        <p v-if="row.type_text === '乘客投诉'" class="blue-normal">乘客投诉</p>
        <p v-else-if="row.type_text === '车主投诉'" class="green-normal">车主投诉</p>
        <p v-else class="gray-normal">{{ row.type_text || '未知类型' }}</p>
      </template>

      <!-- 审核状态 -->
      <template slot-scope="{ row }" slot="complaintStatus">
        <p v-if="row.auth_status_text === '待审核'" class="blue-normal">待审核</p>
        <p v-else-if="row.auth_status_text === '已审核'" class="green-normal">已审核</p>
        <p v-else-if="row.auth_status_text === '已驳回'">
          <span class="gray-normal">已驳回</span>
        </p>
        <p v-else class="gray-normal">{{ row.auth_status_text || '未知状态' }}</p>
      </template>
    </avue-crud>

    <!-- 审核弹框 -->
    <el-dialog title="投诉审核" :visible.sync="reviewDialogVisible" width="500px" :close-on-click-modal="false"
      :modal-append-to-body="true" custom-class="review-dialog" :z-index="9999" :append-to-body="true">
      <el-form :model="reviewForm" :rules="reviewRules" ref="reviewFormRef" label-width="100px">
        <el-form-item label="审核结果" prop="status">
          <el-radio-group v-model="reviewForm.status" @change="handleStatusChange">
            <el-radio :label="1">通过</el-radio>
            <el-radio :label="2">驳回</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 通过时需要诚信扣分 -->
        <el-form-item label="诚信扣分" prop="honesty_deduction" v-if="reviewForm.status === 1">
          <el-input-number v-model="reviewForm.honesty_deduction" :min="0" :precision="2" :step="0.1"
            placeholder="请输入诚信扣分">
          </el-input-number>
        </el-form-item>

        <!-- 驳回时需要拒绝原因 -->
        <el-form-item label="拒绝原因" prop="reject_reason" v-if="reviewForm.status === 2">
          <el-input type="textarea" v-model="reviewForm.reject_reason" :rows="4" placeholder="请输入拒绝原因">
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReview" :loading="reviewLoading">确 定</el-button>
      </div>
    </el-dialog>

    <!-- 查看详情弹框 -->
    <el-dialog title="投诉详情" :visible.sync="viewDialogVisible" width="800px" :close-on-click-modal="false"
      :modal-append-to-body="true" custom-class="view-dialog" :z-index="9999" :append-to-body="true">
      <div class="complaint-detail">
        <!-- 基本信息表格 -->
        <el-table :data="detailTableData" border stripe size="small" class="detail-table">
          <el-table-column prop="label" label="字段" width="120" align="center" class-name="label-column">
            <template slot-scope="scope">
              <span class="field-label">{{ scope.row.label }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="value" label="内容" min-width="200">
            <template slot-scope="scope">
              <div v-if="scope.row.type === 'content'" class="content-cell">
                {{ scope.row.value }}
              </div>
              <div v-else-if="scope.row.type === 'status'" class="status-cell">
                <span :class="getStatusClass(scope.row.value)">{{ scope.row.value }}</span>
              </div>
              <div v-else-if="scope.row.type === 'type'" class="type-cell">
                <span :class="getTypeClass(scope.row.value)">{{ scope.row.value }}</span>
              </div>
              <div v-else class="normal-cell">
                {{ scope.row.value || '暂无' }}
              </div>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关 闭</el-button>
      </div>
    </el-dialog>
  </basic-container>
</template>

<script>
import { mapGetters } from "vuex";
import { getComplaintList, reviewComplaint } from "./api";

export default {
  data () {
    return {
      form: {},
      query: {},
      loading: false,
      searchInfo: {},
      page: {
        currentPage: 1,
        pageSize: 10,
        total: 0,
      },
      selectionList: [],
      option: {
        menuType: "button",
        height: "auto",
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: false,
        index: true,
        indexLabel: "序号",
        searchBtnText: "提交",
        searchBtnIcon: "提交",
        emptyBtnText: "重置",
        emptyBtnIcon: "重置",
        viewBtn: false,
        addBtn: false,
        addBtnText: "添加",
        addBtnIcon: "el-icon-plus",
        editBtn: false,
        editBtnText: "",
        selection: false,
        dialogClickModal: false,
        delBtn: false,
        delBtnText: "",
        labelWidth: 110,
        searchLabelWidth: 100,
        column: [
          {
            label: "投诉类型",
            prop: "type",
            search: true,
            type: "select",
            dicData: [
              {
                label: "乘客投诉",
                value: 1,
              },
              {
                label: "车主投诉",
                value: 2,
              },
            ],
          },
          {
            label: "投诉人",
            prop: "user_nickname",
            search: true,
          },
          {
            label: "投诉对象",
            prop: "complaint_user_nickname",
            search: true,
          },
          {
            label: "投诉行程",
            prop: "itinerary",
            formatter: (row) => {
              return `${row.start_name || ''} → ${row.end_name || ''}`;
            }
          },
          {
            label: "投诉内容",
            prop: "content",
          },
          {
            label: "投诉时间",
            prop: "created_at",
            type: "date",
          },
          {
            label: "单座价格",
            prop: "single_price",
          },
          {
            label: "审核状态",
            prop: "auth_status",
            search: true,
            type: "select",
            dicData: [
              {
                label: "待审核",
                value: 0,
              },
              {
                label: "已审核",
                value: 1,
              },
              {
                label: "已驳回",
                value: 2,
              },
            ],
          },
          {
            label: "审核人",
            prop: "author_realname",
          },
          {
            label: "审核时间",
            prop: "auth_at",
          },

        ],
      },
      resData: [],
      currentItemData: null,
      // 聊天弹框相关数据
      chatDialogVisible: false,
      searchKeyword: "",
      chatMessages: [],
      chatCurrentPage: 1,
      chatPageSize: 10,
      totalMessages: 0,
      currentChatRow: null,
      ownerInfo: {},
      passengersInfo: [],
      // 审核相关数据
      reviewDialogVisible: false,
      reviewLoading: false,
      // 查看详情相关数据
      viewDialogVisible: false,
      reviewForm: {
        id: null,
        status: 1,
        honesty_deduction: 0,
        reject_reason: ''
      },
      reviewRules: {
        status: [
          { required: true, message: '请选择审核结果', trigger: 'change' }
        ],
        honesty_deduction: [
          { required: true, message: '请输入诚信扣分', trigger: 'blur' },
          { type: 'number', min: 0, message: '诚信扣分不能小于0', trigger: 'blur' }
        ],
        reject_reason: [
          { required: true, message: '请输入拒绝原因', trigger: 'blur' }
        ]
      }
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permission.complaint_add, false),
        viewBtn: this.vaildData(this.permission.complaint_view, false),
        delBtn: this.vaildData(this.permission.complaint_delete, false),
        editBtn: this.vaildData(this.permission.complaint_edit, false),
      };
    },
    // 详情表格数据
    detailTableData () {
      if (!this.currentItemData) return [];

      const data = [
        {
          label: '投诉类型',
          value: this.currentItemData.type_text,
          type: 'type'
        },
        {
          label: '审核状态',
          value: this.currentItemData.auth_status_text,
          type: 'status'
        },
        {
          label: '投诉人',
          value: this.currentItemData.user_nickname,
          type: 'normal'
        },
        {
          label: '投诉对象',
          value: this.currentItemData.complaint_user_nickname,
          type: 'normal'
        },
        {
          label: '投诉行程',
          value: `${this.currentItemData.start_name || ''} → ${this.currentItemData.end_name || ''}`,
          type: 'normal'
        },
        {
          label: '投诉内容',
          value: this.currentItemData.content,
          type: 'content'
        },
        {
          label: '投诉时间',
          value: this.currentItemData.created_at,
          type: 'normal'
        },
        {
          label: '单座价格',
          value: this.currentItemData.single_price,
          type: 'normal'
        }
      ];

      // 如果已审核，添加审核相关信息
      if (this.currentItemData.auth_status_text !== '待审核' && this.currentItemData.auth_at) {
        data.push(
          {
            label: '审核人',
            value: this.currentItemData.author_realname,
            type: 'normal'
          },
          {
            label: '审核时间',
            value: this.currentItemData.auth_at,
            type: 'normal'
          }
        );
      }

      return data;
    }
  },
  created () {
    // 初始化加载数据
    this.onLoad(this.page);
  },
  methods: {
    // 获取数据列表
    onLoad (page, search = {}) {
      this.loading = true;
      let param = {
        page: page.currentPage,
        size: page.pageSize,
        user_keyword: this.query.user_nickname || search.user_nickname,
        complaint_user_keyword: this.query.complaint_user_nickname || search.complaint_user_nickname,
        type: this.query.type || search.type,
        auth_status: this.query.auth_status || search.auth_status,
      };

      getComplaintList(param)
        .then((res) => {
          this.resData = res.data.list || [];
          this.page.total = res.data.total || 0;
          this.loading = false;
        })
        .catch((error) => {
          console.error('获取投诉列表失败:', error);
          this.loading = false;
          this.$message.error('获取投诉列表失败');
        });
    },

    // 搜索变化
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      // 调用done回调来结束搜索按钮的加载状态
      if (done) {
        done();
      }
    },

    // 搜索重置
    searchReset (done) {
      this.query = {};
      this.page.currentPage = 1;
      this.onLoad(this.page);
      // 调用done回调来结束重置按钮的加载状态
      if (done) {
        done();
      }
    },

    // 当前页变化
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad(this.page, this.query);
    },

    // 每页大小变化
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
    },

    // 刷新
    refreshChange () {
      this.onLoad(this.page, this.query);
    },

    // 查看详情
    handleView (row, index) {
      this.currentItemData = row;
      this.viewDialogVisible = true;
    },

    // 获取状态样式类
    getStatusClass (status) {
      if (status === '待审核') return 'status-pending';
      if (status === '已审核' || status === '审核通过') return 'status-approved';
      if (status === '已驳回' || status === '审核拒绝') return 'status-rejected';
      return 'status-normal';
    },

    // 获取类型样式类
    getTypeClass (type) {
      if (type === '乘客投诉') return 'type-passenger';
      if (type === '车主投诉') return 'type-driver';
      return 'type-normal';
    },

    // 审核投诉
    handleReview (row, index) {
      this.reviewForm.id = row.id;
      this.reviewForm.status = 1;
      this.reviewForm.honesty_deduction = 0;
      this.reviewForm.reject_reason = '';
      this.reviewDialogVisible = true;
    },

    // 处理审核状态变化
    handleStatusChange (value) {
      // 当状态改变时，清空相关字段
      if (value === 1) {
        this.reviewForm.reject_reason = '';
      } else if (value === 2) {
        this.reviewForm.honesty_deduction = 0;
      }
    },

    // 提交审核
    submitReview () {
      this.$refs.reviewFormRef.validate((valid) => {
        if (valid) {
          this.reviewLoading = true;

          // 根据审核状态构建提交数据
          const submitData = {
            id: this.reviewForm.id,
            auth_status: this.reviewForm.status,
            honesty_deduction: this.reviewForm.status === 1 ? this.reviewForm.honesty_deduction : null,
            reject_reason: this.reviewForm.status === 2 ? this.reviewForm.reject_reason : null
          };

          console.log('提交的审核数据:', submitData);

          reviewComplaint(submitData)
            .then((res) => {
              this.$message.success('审核成功');
              this.reviewDialogVisible = false;
              this.onLoad(this.page, this.query);
            })
            .catch((error) => {
              console.error('审核失败:', error);
              this.$message.error('审核失败');
            })
            .finally(() => {
              this.reviewLoading = false;
            });
        }
      });
    },

    // 行更新
    rowUpdate (row, index, done, loading) {
      // 行更新逻辑
      done();
    },

    // 行保存
    rowSave (row, done, loading) {
      // 行保存逻辑
      done();
    },

    // 行删除
    rowDel (row, done) {
      // 行删除逻辑
      done();
    },

    // 选择变化
    selectionChange (list) {
      this.selectionList = list;
    },

    // 打开前
    beforeOpen (done, type, finish) {
      // 打开前的逻辑
      done();
    },
  },
};
</script>

<style lang="scss" scoped>
.blue-normal {
  color: #0e77d1;
  display: inline-block;
  display: flex;
  align-items: center;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #0e77d1;
    margin-right: 4px;
  }
}

.green-normal {
  color: #00a854;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #00a854;
    margin-right: 4px;
  }
}

.gray-normal {
  color: #aaaaaa;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #aaaaaa;
    margin-right: 4px;
  }
}

.purple-normal {
  color: #8400ff;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #8400ff;
    margin-right: 4px;
  }
}

.orange-normal {
  color: #f59a23;
  display: inline-block;

  &::before {
    content: "";
    display: inline-block;
    width: 10px;
    height: 10px;
    border-radius: 10px;
    background-color: #f59a23;
    margin-right: 4px;
  }
}

.review-dialog,
.view-dialog {
  z-index: 9999 !important;

  .el-dialog__wrapper {
    z-index: 9999 !important;
  }

  .el-dialog {
    z-index: 10000 !important;
  }

  .el-dialog__mask {
    z-index: 9998 !important;
  }
}

// 确保弹窗在最顶层
.el-dialog__wrapper.review-dialog,
.el-dialog__wrapper.view-dialog {
  z-index: 9999 !important;
}

.el-dialog.review-dialog,
.el-dialog.view-dialog {
  z-index: 10000 !important;
}

// 查看详情样式
.complaint-detail {
  .detail-table {
    .field-label {
      font-weight: bold;
      color: #333;
    }

    .content-cell {
      padding: 10px;
      background-color: #f8f9fa;
      border-radius: 4px;
      line-height: 1.6;
      white-space: pre-wrap;
      word-break: break-word;
      min-height: 60px;
    }

    .status-cell {
      .status-pending {
        color: #e6a23c;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #e6a23c;
          margin-right: 6px;
        }
      }

      .status-approved {
        color: #67c23a;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #67c23a;
          margin-right: 6px;
        }
      }

      .status-rejected {
        color: #f56c6c;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #f56c6c;
          margin-right: 6px;
        }
      }
    }

    .type-cell {
      .type-passenger {
        color: #409eff;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #409eff;
          margin-right: 6px;
        }
      }

      .type-driver {
        color: #67c23a;
        font-weight: bold;

        &::before {
          content: "";
          display: inline-block;
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #67c23a;
          margin-right: 6px;
        }
      }
    }

    .normal-cell {
      color: #606266;
    }
  }
}

.chat-dialog {
  position: relative;
  z-index: 2000 !important;

  .el-dialog__body {
    padding: 0 20px;
  }

  .chat-container {
    display: flex;
    flex-direction: column;
    height: 600px;

    .user-info-section {
      display: flex;
      padding: 15px 0;
      border-bottom: 1px solid #ebeef5;

      .user-info {
        flex: 1;
        padding: 0 15px;

        h4 {
          margin: 0 0 10px 0;
          font-size: 16px;
          color: #333;
        }

        p {
          margin: 5px 0;
          font-size: 14px;
          color: #666;
        }
      }
    }

    .search-section {
      padding: 15px 0;

      .el-input {
        width: 100%;
      }
    }

    .chat-content {
      flex: 1;
      overflow-y: auto;
      padding: 10px 0;
      border-top: 1px solid #f0f0f0;
      border-bottom: 1px solid #f0f0f0;

      .empty-message {
        display: flex;
        justify-content: center;
        align-items: center;
        height: 100%;
      }

      .message-item {
        margin-bottom: 15px;
        padding: 10px 15px;
        background-color: #f5f5f5;
        border-radius: 4px;

        &.owner-message {
          background-color: #e6f7ff;
        }

        .message-header {
          display: flex;
          justify-content: space-between;
          margin-bottom: 5px;
          font-size: 14px;

          strong {
            color: #333;
          }

          .message-time {
            color: #999;
            font-size: 12px;
          }
        }

        .message-body {
          font-size: 14px;
          color: #666;
          line-height: 1.5;
        }
      }
    }

    .pagination-section {
      padding: 15px 0;
      text-align: right;
    }
  }
}
</style>
